<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" :width="step === 1 ? '1400' : '700'">
    <el-steps class="mentor-step" :active="step" align-center>
      <el-step
        :title="t('systemUser.mentor.form.step1')"
        :description="t('systemUser.mentor.form.step1Intro')"
      />
      <el-step
        :title="t('systemUser.mentor.form.step2')"
        :description="t('systemUser.mentor.form.step2Intro')"
      />
    </el-steps>
    <el-alert v-if="step === 1" type="error" class="!mb-[10px]">{{
      t('systemUser.mentor.form.warning')
    }}</el-alert>
    <div v-if="step === 1">
      <MentorSelectTable @choose="mentorChoose" />
    </div>
    <div v-if="step === 2">
      <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item :label="t('systemUser.fields.mentorPhoto')" prop="mentorPhoto">
              <UploadImg v-model="formData.mentorPhoto" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <el-button v-if="step === 2" :disabled="formLoading" type="primary" @click="submitForm"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import { UserVO } from '@/api/system/user'
import { FormRules } from 'element-plus'
import MentorSelectTable from './MentorSelectTable.vue'
import { UploadImg } from '@/components/UploadFile'

defineOptions({ name: 'SystemUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const step = ref(1)

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref<Partial<UserVO>>({})
const formRules = reactive({
  mentorPhoto: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('systemUser.fields.mentorPhoto'),
      trigger: 'change'
    }
  ]
} as FormRules)

const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  step.value = 1
  // 重置表单
  formData.value = {}
  formRef.value?.resetFields()

  // 修改时，设置数据
  if (id) {
    step.value = 2
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    await UserApi.evolveUserToMentor(data)
    message.success(t('common.updateSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const mentorChoose = (item: UserVO) => {
  formData.value = item
  step.value = 2
}
</script>

<style lang="scss" scoped>
.mentor-step {
  max-width: 1200px;
  margin: 0 auto 10px;
}
</style>
